<template>
  <div class="app-container">
    <a-card>
      <a-form :model="queryParams" ref="queryRef" layout="inline" v-show="showSearch">
        <a-form-item label="车辆编码" name="vehicleCode">
          <a-input
            v-model:value="queryParams.vehicleCode"
            placeholder="请输入车辆编码"
            allowClear
            @pressEnter="handleQuery"
            style="width: 200px"
          />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="handleQuery">
            <template #icon><SearchOutlined /></template>
            搜索
          </a-button>
          <a-button @click="resetQuery" style="margin-left: 8px">
            <template #icon><ReloadOutlined /></template>
            重置
          </a-button>
        </a-form-item>
      </a-form>

      <div class="table-operations" style="margin-bottom: 16px">
        <a-space>
          <a-button
            type="primary"
            @click="handleAdd"
            v-privilege="'vehicleSys:liveVehicle:add'"
          >
            <template #icon><PlusOutlined /></template>
            新增
          </a-button>
          <a-button
            type="default"
            :disabled="single"
            @click="handleUpdate"
            v-privilege="'vehicleSys:liveVehicle:edit'"
          >
            <template #icon><EditOutlined /></template>
            修改
          </a-button>
          <a-button
            type="primary"
            danger
            :disabled="multiple"
            @click="handleDelete"
            v-privilege="'vehicleSys:liveVehicle:remove'"
          >
            <template #icon><DeleteOutlined /></template>
            删除
          </a-button>
          <a-button
            type="default"
            @click="handleExport"
            v-privilege="'vehicleSys:liveVehicle:export'"
          >
            <template #icon><DownloadOutlined /></template>
            导出
          </a-button>
        </a-space>
<!--        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>-->
      </div>

      <a-table 
        :loading="loading" 
        :dataSource="liveVehicleList" 
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: handleSelectionChange }"
        rowKey="id"
        :pagination="false"
      >
        <a-table-column title="序号" dataIndex="id" align="center" />
        <a-table-column title="车辆编码" dataIndex="vehicleCode" align="center" />
        <a-table-column title="车辆图片" dataIndex="imageUrl" align="center" />
        <a-table-column title="所在车队" dataIndex="teamId" align="center" />
        <a-table-column title="创建时间" dataIndex="createdAt" align="center" :width="180">
          <template #default="{ record }">
            <span>{{ parseTime(record.createdAt, '{y}-{m}-{d}') }}</span>
          </template>
        </a-table-column>
        <a-table-column title="更新时间" dataIndex="updatedAt" align="center" :width="180">
          <template #default="{ record }">
            <span>{{ parseTime(record.updatedAt, '{y}-{m}-{d}') }}</span>
          </template>
        </a-table-column>
        <a-table-column title="操作" align="center" class-name="small-padding fixed-width">
          <template #default="{ record }">
            <a-space>
              <a-button type="link" @click="handleUpdate(record)" v-privilege="'vehicleSys:liveVehicle:edit'">
                <template #icon><EditOutlined /></template>
                修改
              </a-button>
              <a-button type="link" danger @click="handleDelete(record)" v-privilege="'vehicleSys:liveVehicle:remove'">
                <template #icon><DeleteOutlined /></template>
                删除
              </a-button>
            </a-space>
          </template>
        </a-table-column>
      </a-table>

      <div class="table-pagination" style="margin-top: 16px; text-align: right" v-show="total > 0">
        <a-pagination
          :total="total"
          :current="queryParams.pageNum"
          :pageSize="queryParams.pageSize"
          @change="handlePageChange"
          @showSizeChange="handlePageSizeChange"
          show-size-changer
          :show-total="(total) => `共 ${total} 条`"
        />
      </div>

      <!-- 添加或修改直播车辆对话框 -->
      <a-modal :title="title" v-model:open="open" width="500px" :confirm-loading="submitLoading">
        <a-form ref="liveVehicleRef" :model="form" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
          <a-form-item label="车辆编码" name="vehicleCode">
            <a-input v-model:value="form.vehicleCode" placeholder="请输入车辆编码" />
          </a-form-item>
          <a-form-item label="车辆图片" name="imageUrl">
            <a-input v-model:value="form.imageUrl" placeholder="请输入车辆图片" />
          </a-form-item>
          <a-form-item label="所在车队" name="teamId">
            <a-select v-model:value="form.teamId" placeholder="请选择所在车队" allowClear>
              <a-select-option
                v-for="item in teamOptions"
                :key="item.value"
                :value="item.value"
              >
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="创建时间" name="createdAt">
            <a-date-picker 
              v-model:value="form.createdAt"
              value-format="YYYY-MM-DD"
              placeholder="请选择创建时间"
              style="width: 100%"
            />
          </a-form-item>
          <a-form-item label="更新时间" name="updatedAt">
            <a-date-picker 
              v-model:value="form.updatedAt"
              value-format="YYYY-MM-DD"
              placeholder="请选择更新时间"
              style="width: 100%"
            />
          </a-form-item>
        </a-form>
        <template #footer>
          <a-button @click="cancel">取 消</a-button>
          <a-button type="primary" @click="submitForm" :loading="submitLoading">确 定</a-button>
        </template>
      </a-modal>
    </a-card>
  </div>
</template>

<script setup name="LiveVehicle">
import { ref, reactive, toRefs, getCurrentInstance } from 'vue';
import { message, Modal } from 'ant-design-vue';
import {
  SearchOutlined,
  ReloadOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  DownloadOutlined
} from '@ant-design/icons-vue';
import { listLiveVehicle, getLiveVehicle, delLiveVehicle, addLiveVehicle, updateLiveVehicle } from "/@/api/offroad/vehicleSys/liveVehicle";
import { listTeamInfo } from "/@/api/offroad/TeamSys/teamInfo";

const teamOptions = ref([]);
const selectedRowKeys = ref([]);

// 加载车队数据
function loadTeamOptions() {
  listTeamInfo({}).then(response => {
    teamOptions.value = response.data.list.map(item => ({
      label: item.teamName,
      value: item.teamId
    }));
  });
}

const { proxy } = getCurrentInstance();

const liveVehicleList = ref([]);
const open = ref(false);
const loading = ref(true);
const submitLoading = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    vehicleCode: null,
  },
  rules: {
    vehicleCode: [
      { required: true, message: "车辆编码不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询直播车辆列表 */
function getList() {
  loading.value = true;
  listLiveVehicle(queryParams.value).then(response => {
    liveVehicleList.value = response.data.list;
    total.value = response.data.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    vehicleCode: null,
    imageUrl: null,
    teamId: null,
    createdAt: null,
    updatedAt: null
  };
  if (proxy.$refs.liveVehicleRef) {
    proxy.$refs.liveVehicleRef.resetFields();
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    vehicleCode: null,
  };
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selectedKeys, selectedRows) {
  selectedRowKeys.value = selectedKeys;
  ids.value = selectedRows.map(item => item.id);
  single.value = selectedRows.length != 1;
  multiple.value = !selectedRows.length;
}

// 分页页码变化
function handlePageChange(page, pageSize) {
  queryParams.value.pageNum = page;
  queryParams.value.pageSize = pageSize;
  getList();
}

// 分页大小变化
function handlePageSizeChange(current, size) {
  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = size;
  getList();
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  loadTeamOptions();
  open.value = true;
  title.value = "添加直播车辆";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  loadTeamOptions();
  const _id = row.id || ids.value[0];
  getLiveVehicle(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改直播车辆";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["liveVehicleRef"].validate().then(() => {
    submitLoading.value = true;
    if (form.value.id != null) {
      updateLiveVehicle(form.value).then(() => {
        message.success("修改成功");
        open.value = false;
        getList();
      }).finally(() => {
        submitLoading.value = false;
      });
    } else {
      addLiveVehicle(form.value).then(() => {
        message.success("新增成功");
        open.value = false;
        getList();
      }).finally(() => {
        submitLoading.value = false;
      });
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row?.id || ids.value;
  Modal.confirm({
    title: '确认删除',
    content: `是否确认删除直播车辆编号为"${_ids}"的数据项？`,
    onOk() {
      return delLiveVehicle(_ids).then(() => {
        getList();
        message.success("删除成功");
      });
    }
  });
}

/** 导出按钮操作 */
function handleExport() {
  // 这里需要根据实际的导出API进行调整
  console.log('导出功能需要根据实际API实现');
  message.info('导出功能需要根据实际API实现');
}

getList();
</script>